package cn.aicnn.chatssespringboot.service.Impl;

import okhttp3.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class PaintingCommitImpl {

    private static final String API_KEY = "c1VqICOylltMrqF3my74LMcy";
    private static final String SECRET_KEY = "wjD6FMuBPcf9w15yyDKViwpLWY0jYJxo";

    public static void main(String[] args) throws IOException {
        String taskId = submitRequest();
        System.out.println("Task ID: " + taskId);
    }

    public static String submitRequest() throws IOException {
        String token = getAccessToken();

        OkHttpClient client = new OkHttpClient();
        ObjectMapper objectMapper = new ObjectMapper();

        String url = "https://aip.baidubce.com/rpc/2.0/ernievilg/v1/txt2img?access_token=" + token;

        Map<String, Object> payloadMap = new HashMap<>();
        payloadMap.put("text", "中国山水画");
        payloadMap.put("resolution", "1024*1024");
        payloadMap.put("style", "写实风格");
        payloadMap.put("num", 1);

        String payload = objectMapper.writeValueAsString(payloadMap);

        RequestBody body = RequestBody.create(payload, MediaType.parse("application/json"));

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();

        try (Response response = client.newCall(request).execute()) {
            String responseBody = response.body().string();
            System.out.println("Response Body: " + responseBody); // 打印响应体以便调试

            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response + " with body " + responseBody);
            }

            Map<String, Object> result = objectMapper.readValue(responseBody, HashMap.class);
            Map<String, Object> data = (Map<String, Object>) result.get("data");

            if (data == null) {
                throw new IllegalStateException("Response data is null: " + result);
            }

            Object taskIdObject = data.get("taskId");
            if (taskIdObject instanceof Integer) {
                return String.valueOf(taskIdObject);
            } else if (taskIdObject instanceof String) {
                return (String) taskIdObject;
            } else {
                throw new IllegalStateException("Unexpected taskId type: " + (taskIdObject != null ? taskIdObject.getClass().getName() : "null"));
            }
        }
    }

    private static String getAccessToken() throws IOException {
        OkHttpClient client = new OkHttpClient();

        String url = "https://aip.baidubce.com/oauth/2.0/token";
        RequestBody body = new FormBody.Builder()
                .add("grant_type", "client_credentials")
                .add("client_id", API_KEY)
                .add("client_secret", SECRET_KEY)
                .build();

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }

            String responseBody = response.body().string();
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> result = objectMapper.readValue(responseBody, HashMap.class);
            return (String) result.get("access_token");
        }
    }
}
